/* 
 * ----------------------
 * Includes
 * ----------------------
 */
 
 // Standard
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

// SDL
#include <SDL.h>
#include <SDL/SDL_ttf.h>

// GUI
#include "elder_gui.h"

// Context
#include "context.h"

/* 
 * ----------------------
 * Global variables
 * ----------------------
 */

 extern context currentContext;
 
 unsigned char initialized;
 FILE* fd_bright;
 FILE* fd_max;


/* 
 * ----------------------
 * Functions
 * ----------------------
 */
 
 // Backlight initialization
int initBacklightControl(void)
{
    int result = 0;
    int size = 0;
    char buffer[6];
	
	initialized = 0;
	
    fd_bright  = fopen(BACKLIGHT_BRIGHTNESS_SYS_FILE, "w+");
    fd_max = fopen(BACKLIGHT_MAX_BRIGHTNESS_SYS_FILE, "r");

    if( (fd_bright != NULL) && (fd_max != NULL) )
    {
        size = fread( buffer, 1, 6, fd_max );
        currentContext.maxBacklight = atoi(buffer);
        size = fread( buffer, 1, 6, fd_bright);
        currentContext.backlight = atoi(buffer);
        
        initialized = 1;

    } else {
    	result = -1;
        fprintf(stderr,"[Backlight] Can't open %s interface\n", BACKLIGHT_BRIGHTNESS_SYS_FILE);
    }
    
    return result;
}

// Release backlight control
void releaseBacklightControl(void)
{
    if( initialized )
    {
        fclose(fd_bright);
        fclose(fd_max);
        initialized = 0;
    }
}

// 0-100%
void setBrightness(unsigned char aValue)
{
    if( initialized )
    {
        char value[4]; int nchar;
        if( aValue > 100 ) aValue = 100;
        aValue = (aValue * currentContext.maxBacklight) / 100;

        // Send it to hardware
        nchar = sprintf( value, "%d", aValue);
        fwrite( value, 1, nchar, fd_bright );
        fflush( fd_bright );
        
        currentContext.backlight = aValue;
    }
}

/*
 * 0-100 %
 */
unsigned char getBrightness(void)
{
    return( (currentContext.backlight * 100) / currentContext.maxBacklight );
}
